package com.golxen.framework.common.server.game.cmd;


import com.golxen.framework.ClientProtocol;
import com.golxen.framework.GameProtocol;
import com.golxen.framework.PBPacket.PBPacket;
import com.golxen.framework.common.queue.PlayerMQ;
import com.golxen.utils.LogUtil;
import com.googlecode.protobuf.format.JsonFormat;
import com.mysql.cj.util.LogUtils;
import io.netty.channel.ChannelHandlerContext;

public class GameCommandWrapper implements Runnable {

    private ChannelHandlerContext ctx;
    private Runnable r;
    private PBPacket packet;
    private long receiveTime;
    private PlayerMQ player;

    public GameCommandWrapper(ChannelHandlerContext ctx, PBPacket packet, PlayerMQ player) {
        this.ctx = ctx;
        this.r = null;
        this.packet = packet;
        this.player = player;
        this.receiveTime = System.currentTimeMillis();
    }
    public GameCommandWrapper(PlayerMQ player,Runnable r) {
        this.ctx = null;
        this.r = r;
        this.packet = null;
        this.player = player;
        this.receiveTime = System.currentTimeMillis();
    }

    /**
     * 线程池执行消息队列
     */
    @Override
    public final void run() {
//        long beginTime = System.currentTimeMillis();
        Command cmd = null;
        Command.Tuple t = null;
        try {
            if (packet!=null){
                cmd = CommandSet.getCommand(packet.getCode());
                if (cmd == null) {
                    throw new RuntimeException(
                            "playerId=" + packet.getPlayerId() + " code=" + packet.getCode() + " is undefined");
                }
                cmd.execute(ctx, packet);
            }else{
                r.run();
            }

        } catch (Exception e) {
            LogUtil.COMMON.error("", e);
        } finally {
            if (player != null) {
                /* 移除已经执行的指令 */
                player.getCommandQueue().remove();
            }
        }
//        long now = System.currentTimeMillis();
//        long waiteTime = beginTime - receiveTime;
//        long executeTime = now - beginTime;

    }
}
